package top.waikin.mooc.common.service.impl;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.http.HttpMethodName;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import top.waikin.mooc.common.service.COSService;


import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

/**
 * COS实现
 */
public class COSServiceImpl implements COSService {

    @Value("${tencent-cloud.cos.bucketName}")
    private String BUCKET_NAME;
    @Value("${tencent-cloud.cos.expiration}")
    private long EXPIRATION;
    @Autowired
    COSClient cosClient;

    @Override
    public URL generateUploadUrl() {
        long expireEndTime = System.currentTimeMillis() + EXPIRATION * 1000;    // 上传链接五分钟失效
        Date date = new Date(expireEndTime);
        return cosClient.generatePresignedUrl(BUCKET_NAME, generateRandomKey(), date, HttpMethodName.PUT, new HashMap<>(), new HashMap<>());
    }

    private String generateRandomKey() {
        return UUID.randomUUID().toString().replaceAll("-", "").toLowerCase();
    }
}
